﻿using AutoMapper;
using B.S.BasicData.API.Read.Application.Command.Menu;
using B.S.BasicData.API.Read.DTOS.UserRoleMenu;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Read.Application.Handler.Menu
{
    /// <summary>
    /// 根据角色Id反填菜单权限信息请求命令处理类
    /// </summary>
    public class FanTianMenuIdByRoleIdHandler:IRequestHandler<FanTianMenuIdByRoleIdCommand,ApiResult<List<RoleMenuDTO>>>
    {
        IBaseRepository<RoleMenuModel> roleMenuRep;
        IBaseRepository<MenuModel> menuRep;
        IMapper mapper;

        public FanTianMenuIdByRoleIdHandler(IBaseRepository<RoleMenuModel> roleMenuRep, IBaseRepository<MenuModel> menuRep, IMapper mapper)
        {
            this.roleMenuRep = roleMenuRep;
            this.menuRep = menuRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<RoleMenuDTO>>> Handle(FanTianMenuIdByRoleIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<RoleMenuDTO>> res = new ApiResult<List<RoleMenuDTO>>();

                var menus = roleMenuRep.GetAll().Where(x => x.RoleId == request.roleId && !x.IsDeleted);
                var model = mapper.Map<List<RoleMenuDTO>>(menus);

                foreach (var item in model)
                {
                    item.MenuId = menuRep.GetAll().Where(x => x.Id == item.MenuId).Select(x => x.Id).FirstOrDefault();
                    item.MenuName = menuRep.GetAll().Where(x => x.Id == item.MenuId).Select(x => x.MenuName).FirstOrDefault();
                }

                res.Msg = "根据角色Id获取菜单权限信息";
                res.Code = ApiEnum.Success;
                res.Data = model;
                return Task.FromResult(res);

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
